package com.dgut.admin.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.dgut.common.utils.ApiException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author IT00ZYQ
 * @date 2021/6/16 13:28
 **/
public class ExcelUtil {

    /**
     * 导出Excel
     * @param response
     * @param list 数据
     * @param fileName 文件名称
     * @param sheetName 表名
     * @param clazz 指定导出模板类的类型
     */
    public static void writeExcel(HttpServletResponse response, List<?> list,
                                  String fileName, String sheetName, Class<?> clazz){
        EasyExcel.write(getOutputStream(fileName, response), clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .doWrite(list);
    }


    /**
     * 读取Excel中的数据
     * @param file
     * @param clazz
     * @param listener
     */
    public static void readExcel(MultipartFile file, Class<?> clazz, AnalysisEventListener<?> listener) {
        ExcelReader excelReader = null;
        try {
            excelReader = EasyExcel.read(getInputStream(file), clazz, listener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
        } finally {
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
    }

    /**
     * 导出文件时为Writer生成OutputStream
     * @param fileName
     * @param response
     * @return
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new ApiException("导出excel表格失败!");
        }
    }


    /**
     * 导入文件时为Reader生成InputStream
     * @param file
     * @return
     */
    private static InputStream getInputStream(MultipartFile file) {
        try {
            return file.getInputStream();
        } catch (IOException e) {
            throw new ApiException("导入excel表格数据失败!");
        }
    }
}

